package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.dataformat.yaml.util.StringQuotingChecker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.util.Json;
import org.aspectj.apache.bcel.ExceptionConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.sky.entity.Orders.CANCELLED;
import static com.sky.entity.Orders.REFUND;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //整理业务异常，并处理（地址簿为空，购物车数据为空）
        /**
         * 判断地址簿是否为空，为空则抛出异常
         */
            //查询 传入的地址id的 地址信息
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
            //判断地址信息是否为空
        if (addressBook == null){
            //抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        /**
         * 判断购物车数据为空
         */
            //获取当前用户id
        Long currentUserId = BaseContext.getCurrentId();
            //因为shoppingCartMapper.list()传入的为shoppingCart类型，所以把当前用户的ID封装到一个shoppingCart对象
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(currentUserId);
            //根据用户的Id查询购物车
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list==null){
            //抛出购物车为空异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //插入一条订单
        Orders orders = new Orders();
            //拷贝
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
            //补全信息
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
            //使用时间戳（转String）作为订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());
        orders.setUserId(currentUserId);
            //向订单表插入数据
        orderMapper.insert(orders);
        //向订单明细表插入多条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();//用于封装orderDetail，用于动态SQL插入
        for (ShoppingCart cart : list){
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            //由于在插入信息时使用了useGeneratekey，返回了主键值，所以可以获得订单ID
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
            //向订单表插入数据
            orderDetailMapper.insert(orderDetailList);
        //清空购物车
        shoppingCartMapper.delete(currentUserId);
        /**
         * 封装返回数据
         */
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())//封装订单表中的id
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }
    /**
     * 订单支付（直接成功）
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        // 模拟支付成功
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);

        // 更新订单状态
        Integer OrderPaidStatus = Orders.PAID; // 支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED; // 订单状态，待接单
        LocalDateTime check_out_time = LocalDateTime.now();
        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, ordersPaymentDTO.getOrderNumber());
        /**
         * websocket
         */
        //根据订单号和用户id查询订单
        Orders ordersDB = orderMapper.getByIdAndNumber(userId,ordersPaymentDTO.getOrderNumber());
        //通过websocket向客户端浏览器发送数据 type orderid content
        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号"+ordersDB.getNumber());
        //转成json字符串
        String jsonString = JSON.toJSONString(map);
        //向页面推送消息
        webSocketServer.sendToAllClient(jsonString);
        return vo;
    }
    /**
     * 历史订单分页查询
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult page(int pageNum, int pageSize, Integer status) {
        PageHelper.startPage(pageNum,pageSize);
        //把当前用户id和订单状态封装起来
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        //分页条件查询
            //根据userId和status 查找订单
        Page<Orders> pages = orderMapper.pageQuerry(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        for (Orders page : pages){
            //封装订单
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(page,orderVO);
            //查找订单详细
            Long orderId = page.getId();
            List<OrderDetail> orderDetail = orderDetailMapper.getById(orderId);
            //封装订单详细
            orderVO.setOrderDetailList(orderDetail);
            //封装返回的集合，包含订单和订单详细
            list.add(orderVO);
        }
        //返回 总页数，包含订单和订单详细的集合
        return new PageResult(pages.getTotal(),list);
    }
    /**
     * 根据订单Id查询订单明细
     * @param id
     * @return
     */
    @Override
    public OrderVO getDetails(Long id) {
        Orders order = orderMapper.getById(id);
        List<OrderDetail> orderDetail = orderDetailMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        orderVO.setOrderDetailList(orderDetail);
        return orderVO;
    }
    /**
     * 根据订单Id查询订单明细
     * @param id
     * @return
     */
    @Override
    public void cancel(Long id) {
        //判断订单是否存在，不存在返回错误信息
        Orders orders = orderMapper.getById(id);
        if (orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //待接单后不能取消 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        Integer status = orders.getStatus();
        if (status>2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //待接单情况下需要退款
        if (status==2){
            //调用微信的退款接口
            //修改订单状态为已退款
            orders.setPayStatus(orders.REFUND);
        }
        //更新订单状态，取消原因，取消时间
        orders.setStatus(orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }
    /**
     * 再来一单
     * @param id
     */
    @Override
    public void moreOne(Long id) {
        //根据id查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getById(id);
        //使用Stream API 把一个订单详情对象转为一个购物车对象
        List<ShoppingCart> shoppingCart = orderDetailList.stream().map(x->{
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(x,cart,"id");
            cart.setCreateTime(LocalDateTime.now());
            cart.setUserId(BaseContext.getCurrentId());
            return cart;
        }).collect(Collectors.toList());
        //向购物车表中插入数据
        shoppingCartMapper.insertBanch(shoppingCart);
    }
    /**
     * 管理端分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
            //根据传进来的数据查询orders表
        Page page = orderMapper.pageQuerry(ordersPageQueryDTO);
            //把数据封装到List<OrderVO>中，调用getOrderVo方法
        List<OrderVO> orderVOList = getOrderVO(page.getResult());
        return new PageResult(page.getTotal(),orderVOList);
    }

    @Override
    public OrderVO details(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getById(id);
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }
    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statusCount() {
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }
    /**
     * 商家接单
     * @param ordersConfirmDTO
     * @return
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }
    /**
     * 商家拒单
     * @param ordersRejectionDTO
     * @return
     */
    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) {
        //判断订单是否为 TO_BE_CONFIRMED 待接单
       Orders orderMapperById  = orderMapper.getById(ordersRejectionDTO.getId());
        Integer status = orderMapperById.getStatus();
        if (status == null || !status.equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //执行跟新操作
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }
    /**
     * 商家取消订单
     * @param ordersCancelDTO
     * @return
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = Orders.builder()
            .id(ordersCancelDTO.getId())
            .cancelTime(LocalDateTime.now())
            .cancelReason(ordersCancelDTO.getCancelReason())
            .status(Orders.CANCELLED)
            .build();
        orderMapper.update(orders);
    }
    /**
     * 订单派送
     * @param id
     * @return
     */
    @Override
    public void delivery(Long id) {
        //判断订单是否存在
        Orders orderMapperById = orderMapper.getById(id);
        if (orderMapperById.getStatus()==null||!orderMapperById.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
            .status(Orders.DELIVERY_IN_PROGRESS)
            .id(id)
            .build();
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        //判断订单是否存在
        Orders orderMapperById = orderMapper.getById(id);
        if (orderMapperById.getStatus()==null||!orderMapperById.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .id(id)
                .build();
        orderMapper.update(orders);
    }
    /**
     * 用户催单
     * @param id 订单id
     * @return
     */
    @Override
    public void reminder(Long id) {
        Orders orderMapperById = orderMapper.getById(id);
        if (orderMapperById==null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号"+orderMapperById.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }


    /**
     * 私有方法
     */
    //封装方法
    private List<OrderVO> getOrderVO(List<Orders> orders){
        List<OrderVO> orderVOArrayList = new ArrayList<>();
        //判断订单是否为空
        if (orders!=null){
            //封装OrderVO数据
            for (Orders order : orders){
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order,orderVO);
                //通过操作订单详情表，通过Stream API拼接 菜品名*菜品数量；并返回
                String orderDishes = getOrderDishesStr(order);
                //设置菜品信息 菜品名*菜品数量；
                orderVO.setOrderDishes(orderDishes);
                //台南佳orderVO到orderVO的列表里并返回
                orderVOArrayList.add(orderVO);
            }
        }
        return orderVOArrayList;
    }
    //拼接字符串
    private String getOrderDishesStr(Orders order){
        //查询菜品订单信息中的 菜品信息 以及 数量
        List<OrderDetail> orderDetailList = orderDetailMapper.getById(order.getId());
        //拼接 菜品信息 * 数量
        List<String> stringList = orderDetailList.stream().map(x->{
            //拼接后的字符串
           String orderDish = x.getName()+"*"+x.getNumber()+";";
           return orderDish;
        }).collect(Collectors.toList());
        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", stringList);
    }
}
